/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.db;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author janksenhu
 */
public class DataBase {
    
    private Database db;

    public DataBase() {
       EnvironmentConfig envConfig = new EnvironmentConfig();
       envConfig.setAllowCreate(true);
       envConfig.setCacheSize(102400);
       try {
            Environment env = new Environment(new File("E:\\ci\\db"),envConfig);

            DatabaseConfig dbConfig = new DatabaseConfig();
            dbConfig.setAllowCreate(true);

            db = env.openDatabase(null, "myDB", dbConfig);
        
       } catch (DatabaseException e) {
        e.printStackTrace();
       }
    }
    
    
    public void close() {
       try {
        if(db != null) {
         db.close();
        }
       } catch (DatabaseException e) {
        e.printStackTrace();
       }
    }

    public String getValue(String key) throws Exception {
       DatabaseEntry queryKey = new DatabaseEntry();
       DatabaseEntry value = new DatabaseEntry();
       queryKey.setData(key.getBytes("UTF-8"));
       OperationStatus status = db.get(null, queryKey, value,
         LockMode.DEFAULT);
       if (status == OperationStatus.SUCCESS) {
        return new String(value.getData());
       }
       return null;
    }

    public boolean setValue(String key, String value) {
       
       byte[] theKey;
        try {
            theKey = key.getBytes("UTF-8");
            byte[] theValue = value.getBytes("UTF-8");
            System.out.println(db);
            OperationStatus status = db.put(null, new DatabaseEntry(theKey),
              new DatabaseEntry(theValue));
            if(status == OperationStatus.SUCCESS) {
             return true;
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
        }
       return false;                          
    }
    
}
